package com.ellricky.newtv

import android.content.Intent
import android.content.pm.ActivityInfo
import android.net.Uri
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.andr.common.ui.activity.BaseActivity
import com.andr.common.ui.mvp.BasePresenter
import com.andr.common.util.EmptyUtil
import com.andr.common.util.ToastUtil
import com.bumptech.glide.Glide
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.entity.newtv.TvUserInfo
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.util.EAppUtil
import com.ellricky.baselib.util.NewEntityCallback
import com.ellricky.baselib.util.jump
import com.ellricky.newtv.bean.TvCourseDetail
import com.ellricky.newtv.bean.TvRefreshUser
import com.ellricky.newtv.dialog.UserInfoChangeDialogFragment
import com.ellricky.newtv.utils.CacheToken
import com.ellricky.newtv.utils.UriUtils
import kotlinx.android.synthetic.main.activity_new_tv_user_info.*

class NewTvUserInfoActivity : BaseActivity<Void, BasePresenter<Void>>() {

    private var dialog: UserInfoChangeDialogFragment? = null

    private val tvUserInfo: TvUserInfo? by lazy {
        LocalCacheUtil.readTvUserInfo()
    }

    override fun getContentLayout(): Int {
        return R.layout.activity_new_tv_user_info
    }

    override fun setOrientation() {
        this.requestedOrientation =
            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
    }


    override fun initUIView() {
        CacheToken.verifyToken()
        tv_cancel.setOnClickListener(this)
        tv_logout.setOnClickListener(this)
        tv_change_info.setOnClickListener(this)
        tv_contact.setOnClickListener(this)
        tvUserInfo?.also {
            tv_name.text = it.U_Name
            tv_create_time.text = it.creatTime
            tv_end_time.text = it.endDate
            if (it.isEnd == 1) {
                tv_contact.visibility = View.VISIBLE
                tv_contact.text = tv_contact.text.toString().plus("您的账号已到期，请联系管理员重新激活")
                tv_end_time.setTextColor(ContextCompat.getColor(this, R.color.red))
            }
            it.courseList.forEach { course ->
                val textview = createCourseTextView(course.course_name)
                cl_layout.addView(textview)
                flow.addView(textview)
            }
            Glide.with(this).load(it.E_Head).into(iv_avatar)
        }
    }

    private fun createCourseTextView(text: String): TextView {
        val textView = TextView(this)
        textView.layoutParams = ViewGroup.LayoutParams(
            resources.getDimension(R.dimen.dp_80).toInt(),
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        textView.setTextColor(ContextCompat.getColor(this, R.color.white))
        textView.text = text
        textView.textSize = 12f
        textView.id = View.generateViewId()
        return textView
    }

    override fun onClickView(v: View) {
        super.onClickView(v)
        when (v.id) {
            R.id.tv_cancel -> finish()
            R.id.tv_logout -> {
                LocalCacheUtil.tvLogout()
                finish()
            }
            R.id.tv_change_info -> {
                dialog = UserInfoChangeDialogFragment()
                dialog?.show(supportFragmentManager, "")
                dialog?.setOnUserInfoChangeListener(object :
                    UserInfoChangeDialogFragment.OnUserInfoChangeListener {
                    override fun onSelectAvatar() {
                        val intent = Intent(Intent.ACTION_GET_CONTENT)
                        intent.type = "image/*"
                        intent.addCategory(Intent.CATEGORY_OPENABLE)
                        startActivityForResult(intent, 1)
                    }

                    override fun onConfirm(nickName: String, avatar: String) {
                        modifyUserInfo(nickName, avatar)
                    }
                })
            }
            R.id.tv_contact -> {
                jump<NewTvConnectActivity>()
            }
        }
    }

    private fun modifyUserInfo(nickName: String, avatar: String) {
        val url = EAppUtil.getTvApiHost()
        val paramMap = mutableMapOf(
            "action" to "EditDetail",
            "nick" to nickName,
            "eid" to tvUserInfo?.eid,
            "head" to avatar,
            "token" to tvUserInfo?.token
        )
        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewEntityCallback<TvRefreshUser>(this, false) {
                override fun onSuccess(file: TvRefreshUser, var2: String?) {
                    if (tvUserInfo != null) {
                        tvUserInfo?.E_Head = file.head
                        tvUserInfo?.U_Name = file.nick
                        Glide.with(this@NewTvUserInfoActivity).load(file.head).into(iv_avatar)
                        tv_name.text = file.nick
                        LocalCacheUtil.saveTvUser(tvUserInfo)
                    }
                }
            }, this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        try {
            val uri: Uri = data?.data ?: return
            val path = UriUtils.getPath(this, uri)
            if (path.isNotEmpty()) {
                // 接口提交
                if (EmptyUtil.isEmpty(path)) {
                    ToastUtil.show(this, "图片路径为空")
                    return
                }
                dialog?.setSelectAvatar(path)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}